<template>
  <div class="content">
    <t-dialog
        placement="center"
        width="504"
        v-model:visible="visible"
        header="批量导入"
        :onClose="onClose"
        destroy-on-close
    >
      <template #body>
        <!--        <t-radio-group default-value="1" @change="onChange">-->
        <!--          <t-radio value="1">新增</t-radio>-->
        <!--          <t-radio value="2">更新</t-radio>-->
        <!--        </t-radio-group>-->

        <div class="failBox">
          <div class="info"></div>
          <div class="downLoad">点击下载错误报告 </div>
        </div>

        <div class="uploadBox">
          <t-upload
              ref="uploadRef"
              v-model="files"
              :auto-upload="autoUpload"
              withCredentials
              method="POST"
              :accept="accept"
              :headers="queryHeaders"
              :theme="display"
              :data="queryBody"
              :abridge-name="[10, 8]"
              draggable
              :action="uploadUrl"
              :before-upload="beforeUpload"
              @success="handleSuccess"
              :showUploadProgress="true"
              @progress="onProgress"
              @fail="handleFail"
          >
          </t-upload>
          <span v-if="showDel" class="delBtn" @click="deleteFile">删除</span>
        </div>
        <div class="uploadModel" @click="handleTemplateDownload">
          <svg-icon
              :name="'icon-upload'"
              class-name="upload-svg-icon"
          ></svg-icon>
          <span class="text">{{ props.templateText }}</span>
        </div>
        <div class="btnBox">
          <t-button class="resetBtn" @click="close" variant="text">取消</t-button>
          <t-button class="uploadBtn" theme="primary" variant="base" :disabled="files.length === 0" @click="uploadFiles">开始上传</t-button>
        </div>
      </template>
    </t-dialog>

  </div>
</template>

<script setup>
import { ref, getCurrentInstance, watch, reactive } from 'vue';
import { MessagePlugin } from 'tdesign-vue-next';
import auth from '@/utils/auth.js'

const emit = defineEmits()
const props = defineProps({
  openUpload: {
    type: Boolean,
    default: false
  },
  CloseUpload: {
    type: Function,
    default: () => {}
  },
  templateText: {
    type: String,
    default: '下载模版'
  },
  downloadTemplate: { // 下载模版事件
    type: Function,
    default: () => {}
  },
  queryBody: { // 上传请求体
    type: Object,
    default: {}
  },
  uploadUrl: { // action
    type: String,
    default: ''
  },
  accept: {
    type: String,
    default: ''
  }
})
const queryHeaders = ref({
  Authorization: "Bearer " + auth.getToken(),
})
// 弹窗开关
const visible = ref(false)
watch(() => props.openUpload, (newVal, oldVal) => {
  visible.value = newVal
})
const onClose = () => {
  emit('closeUpload', false)
}
// radio 按钮
const onChange = (checkedValues) => {
  console.log('checkedValues', checkedValues)
}
// 上传
const display = ref('file');
const files = ref([]);
const uploadRef = ref();
const progress = ref(0);
const autoUpload = ref(false);
const fileSize = ref(0)

const showDel = ref(false)

const beforeUpload = (file) => {
  showDel.value = true
};
const deleteFile = () => {
  showDel.value = false
  files.value = []
}

// 上传成功
const handleSuccess = ({ file }) => {
  console.log('上传成功回调函数', file)
  // MessagePlugin.success(`文件 ${file.name} 上传成功`);
  if(file.response.code) { // 导入成功
  } else { // 导入失败
    console.log('file.response', file.response.replace("\"","").replace("\"",""))
    const blob = new Blob([file.response], {
      // type: 'application/vnd.ms-excel;charset=utf-8'
      type: 'application/octet-stream'
    })

    console.log('blob', blob)

    // const blob = dataURItoBlob(
    //     "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," +
    //     file.response
    // )

    const url = URL.createObjectURL(blob) //把blob对象转成一个url
    console.log('url', url)

    //创建一个a标签
    const a = document.createElement("a");
    a.href = url; //给a标签上的href属性加上地址
    a.download = `错误报告${new Date().getTime()}.xlsx`; //下载名称
    document.body.appendChild(a); //将a标签添加到文档对象中
    a.click(); //调点击事件
    document.body.removeChild(a); // 一次性的，用完就删除a标签
  }
};

// 上传失败
const handleFail = ({ file }) => {
  console.log('上传失败回调函数', file)
  // MessagePlugin.error(`文件 ${file.name} 上传失败`);
};

// 下载模版
const handleTemplateDownload = () => {
  props.downloadTemplate()
}
const uploadFiles = () => {
  showDel.value = false
  console.log('开始上传', uploadRef.value)
  uploadRef.value.uploadFiles();
};

// 关闭弹窗
const close = () => {
  files.value = []
  emit('closeUpload', false)
}

const onProgress = (file) => {
  console.log('progress', file)
}


const dataURItoBlob = (base64Data) => {
  let byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0) {
    byteString = window.atob(base64Data.split(',')[1]);
  } else {
    byteString = window.unescape(base64Data.split(',')[1]);
  }
  let mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  let ia = new Uint8Array(byteString.length);
  for (let i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], { type: mimeString });
}

</script>

<style lang="scss" scoped>
.content {
  :deep(.t-dialog__ctx .t-dialog) {
    padding: 26px 30px 0 30px !important;
    .t-dialog__header {
      .t-dialog__header-content {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.9);
      }
    }
    .t-dialog__body {
      padding-top: 39px;
      padding-bottom: 20px;
      .t-radio-group {
        .t-radio__label {
          font-size: 12px;
          font-weight: 400;
          color: rgba(92, 91, 91, 1);
        }
      }
      .failBox {
        margin-top: 20px;
        height: 28px;
        border-radius: 6px;
        background: rgba(254, 240, 240, 1);
        padding: 3px 11px 3px 11px;
        display: flex;
        .info {}
        .downLoad {
          margin-left: auto;
          font-size: 13px;
          font-weight: 400;
          text-decoration-line: underline;
          color: rgba(227, 77, 89, 1);

        }
      }
      .uploadBox {
        position: relative;
        .delBtn {
          position: absolute;
          right: 32px;
          top: 50%;
          transform: translateY(-50%);
          cursor: pointer;
          font-size: 14px;
          font-weight: 400;
          color: rgba(30, 117, 254, 1);
        }
      }
      .t-upload {
        margin-top: 20px;
        .t-upload__dragger {
          padding: 0 32px;
          width: 100%;
          height: 133px;
          border-radius: 6px;
          .customBox {
            font-size: 16px;
            font-weight: 400;
            color: rgba(49, 129, 254, 1);
            span {
              display: inline-block;
              margin: 0 5px;
            }
          }
        }
        .t-upload__dragger:hover {
          background: rgba(247, 250, 255, 1);
          border: 1px dashed rgba(30, 117, 254, 1);
        }
        .t-upload__trigger {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        }

        .t-upload__dragger-progress {
          align-items: center;
        }
        .t-upload__dragger-progress-info {
          .t-upload__dragger-btns {
            display: none;
          }
        }
        .t-upload__dragger-progress-info small:nth-child(3) {
          display: none;
        }
      }
      .uploadModel {
        width: 120px;
        margin-top: 8px;
        display: flex;
        align-items: center;
        .upload-svg-icon {
          height: 16px;
          width: 16px;
          display: inline-block;
          cursor: pointer;
        }
        .text {
          font-size: 10px;
          font-weight: 400;
          text-decoration-line: underline;
          color: rgba(30, 117, 254, 1);
          cursor: pointer;
          padding-left: 4px;
        }
      }
      .btnBox {
        text-align: right;
        .resetBtn {
          width: 60px;
          height: 28px;
          background: rgba(255, 255, 255, 1);
          color: rgba(0, 0, 0, 0.9);
          font-size: 14px;
          font-weight: 400;
          margin-right: 8px;
        }
        .uploadBtn {
          width: 88px;
          height: 28px;
          opacity: 1;
          background: rgba(30, 117, 254, 1);
          color: rgba(255, 255, 255, 0.9);
          font-size: 14px;
          font-weight: 400;
          border: none;
        }
        .t-is-disabled {
          color: rgba(255, 255, 255, 0.9);
          background: rgba(212, 227, 252, 1) !important;
        }
      }
    }
    .t-dialog__footer {
      display: none;
    }
  }
}
</style>
